package com.ygxsk.carhome.ui.property;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventRepair;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.PropertyRepairBean;
import com.ygxsk.carhome.response.PropertyRepairOutSideBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.PropertyRepairAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023/12/28  18:23
 * @Description:物业报修的 -历史记录
 */
public class PropertyRepairActivity extends ErrorActivity implements ErrorParentExtraSingle {

//    private String messageNull = "暂无报修提交~";

    @BindView(R.id.refreshLayoutinrepair)
    SmartRefreshLayout refreshLayoutInRepair;

    @BindView(R.id.recyclerViewinrepair)
    RecyclerView recyclerViewInRepair;


    //跳转界面的标识
    private int jumpFromFlag;

    //最后一条上传的id的信息内容
    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    //报修历史记录的
    private ArrayList<PropertyRepairBean> mDatasResources = new ArrayList<>();

    private PropertyRepairAdapter propertyRepairAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_property_repair;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }


    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_my_repair_history));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
//                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里右上角没有东西的
        toolbarHelper.setLayoutRight(true, 0, "", null);

        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 0, "添加", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //快速双加的限制，
//                // : 2023-07-11 16:18 添加预约维保的信息，到提交表单页面；
//                Bundle extra_bundle = new Bundle();
////                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //填充recyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(PropertyRepairActivity.this);
        recyclerViewInRepair.setLayoutManager(layoutManager);

        //============================================================================================================
        propertyRepairAdapter = new PropertyRepairAdapter(R.layout.propertyrepairtransadapter, mDatasResources);

        if (propertyRepairAdapter != null) {

            recyclerViewInRepair.setAdapter(propertyRepairAdapter);

            propertyRepairAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                    PropertyRepairBean propertyRepairBean = (PropertyRepairBean) adapter.getItem(position);

                    //2018年05月30日发现双击跳转了两次内容
                    if (!DoubleClickListener.isFastDoubleClick()) {

                        if (propertyRepairBean != null) {

                            Bundle bundle = new Bundle();
                            bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMPFROM_PROPERTY_ACTIVITY);
                            bundle.putString(ExtraKey.EXTRA_REPAIR_REPAIRID, propertyRepairBean.getRepairId());

                            //携带商品整个实体？
                            ActivityUtils.startActivity(bundle, RepairdDetailActivity.class);

                        }

                    }

                }
            });

        }


        //添加适配器的子view点击事件内容
        propertyRepairAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    PropertyRepairBean propertyRepairBeanItem = (PropertyRepairBean) adapter.getItem(position);

                    switch (view.getId()) {

                        case R.id.layoutcall: {//拨打电话

                            //拨打电话布局内容-需要添加访问权限
                            final String phoneNumber = propertyRepairBeanItem.getTelephone();
                            //测试代码，测试放开
//                            final String phoneNumber  = "18810042043";

                            if (!TextUtils.isEmpty(phoneNumber)) {

//                                showAlertViewPhoneNumber(phoneNumber);

                                clickButton_toCallPhone(mActivityInstance, phoneNumber, CallHistoryBusinessType.BUSINESSTYPE_2.getIndex());

//                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.CALL_PHONE)) {
//
//                                    CommUtils.authorityRequest(mActivityInstance, ConstantApi.MATERIALDIALOG_AUTHORITY_CONTENT_CALLPHONE, new AuthorityCallbackListener() {
//                                        @Override
//                                        public void doSomeThing() {
//
//                                            AndPermission.with(PropertyRepairActivity.this)//
//                                                    .runtime()//
//                                                    .permission(Permission.CALL_PHONE)//拨打电话权限//
//                                                    .rationale(new RuntimeRationale())//
//                                                    .onGranted(new Action<List<String>>() {//
//                                                        @Override
//                                                        public void onAction(List<String> permissions) {//
//
//                                                            showAlertViewPhoneNumber(phoneNumber);//
//
//                                                        }
//                                                    }).onDenied(new Action<List<String>>() {//
//                                                        @Override
//                                                        public void onAction(List<String> permissions) {//
//
//                                                            //CommUtils.displayToastShort(PropertyRepairActivity.this,"获取权限失败");
//                                                            if (AndPermission.hasAlwaysDeniedPermission(PropertyRepairActivity.this, permissions)) {
//                                                                mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, PropertyRepairActivity.this, permissions);
//                                                            }
//                                                        }
//                                                    }).start();
//
//                                        }
//                                    });
//
//                                } else {
//                                    showAlertViewPhoneNumber(phoneNumber);//
//                                }

                            } else {

//                                CommUtils.displayToastShort(PropertyRepairActivity.this, ConstantApi.ALERTVIEW_GETPHONE_INFO_FAIL);
                                ToastUtils.showShort(getResources().getString(R.string.getphoneinfofail));

                            }

                            break;
                        }

//                        case R.id.layoutpingjia: {//评价内容

//                            Bundle bundle = new Bundle();
//                            bundle.putString(ConstantApi.EXTRA_REPAIR_REPAIRID, propertyRepairBeanItem.getRepairId());
//                            ActivityUtils.startActivity(bundle, RepairEvaActivity.class);

//                            break;
//                        }

//                        case R.id.layoutworkerorderqianzi: {//工单签字内容

//                            Bundle bundle = new Bundle();
//                            bundle.putString(ConstantApi.EXTRA_REPAIR_REPAIRID, propertyRepairBeanItem.getRepairId());
//                            ActivityUtils.startActivity(bundle, WorkQianZiActivity.class);

//                            break;
//                        }

                        case R.id.layoutlook: {//查看报修进度内容

                            Bundle bundle = new Bundle();
                            bundle.putString(ExtraKey.EXTRA_PAYMENT_RECEIPTID, propertyRepairBeanItem.getRepairId());
                            ActivityUtils.startActivity(bundle, RepairProgressTwoActivity.class);

                            break;
                        }

                        default:
                            break;
                    }
                }

            }
        });


        if (refreshLayoutInRepair != null) {

            refreshLayoutInRepair.setOnRefreshListener(new OnRefreshLoadMoreListener() {

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            gainDatas();

                            refreshLayout.finishRefresh();

                        }
                    });

                }

                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            getServerDatas();

                            refreshLayout.finishLoadMore();

                        }
                    });
                }
            });

        }

    }


    @Override
    protected void gainDatas() {

        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
        }

        if (propertyRepairAdapter != null) {
            propertyRepairAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInRepair, false);
        }

    }


    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//      map.put(Parameterkey.classify, FeePaymentWaterOrEleType.FEEPAYTYPE_ELE.getIndex());

        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETVILLAGEREPAIRLIST_URL);
        addLogUpLoadInfo.setUrlPath(ApiService.getVillageRepairList_url);
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getVillageRepairList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeElectricFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PropertyRepairOutSideBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        methodNotSuccessData(what_method, serverCode, serverMessage);

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                        loadingGone();

                        setEnableLoadmore(refreshLayoutInRepair, true);

                    }
                }).subscribe(new Consumer<PropertyRepairOutSideBean>() {
                    @Override
                    public void accept(PropertyRepairOutSideBean propertyRepairOutSideBean) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //----------------------------------------------------------------------------------------------------
                        if (propertyRepairOutSideBean != null) {

                            ArrayList<PropertyRepairBean> propertyRepairBeanArrayList = propertyRepairOutSideBean.getDataList();

                            if (propertyRepairBeanArrayList != null && !propertyRepairBeanArrayList.isEmpty()) {

                                if (mDatasResources != null) {
                                    mDatasResources.addAll(propertyRepairBeanArrayList);
                                }

                            }

                        }
                        //---------------------------------------------------------------------------------------------------

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDatasResources != null && mDatasResources.isEmpty()) {

                            //同时禁用加载更多；
                            setEnableLoadmore(refreshLayoutInRepair, false);

                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

                        }

                        if (propertyRepairAdapter != null) {
                            propertyRepairAdapter.notifyDataSetChanged();
                        }

                        //给分页值
                        pagination_upLoad = propertyRepairOutSideBean.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInRepair, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInRepair, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        setEnableLoadmore(refreshLayoutInRepair, false);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETVILLAGEREPAIRLIST_URL: {

                if (mDatasResources != null && mDatasResources.isEmpty()) {

                    setEnableLoadmore(refreshLayoutInRepair, false);

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadRepair(EventRepair eventRepair) {

        if (eventRepair != null) {

            if (eventRepair.getMessage() == ExtraValue.EVENTBUS_REPAIRCANCEL ||//取消报修
                    eventRepair.getMessage() == ExtraValue.EVENTBUS_REPAIR_EVAED ||//评价完毕
                    eventRepair.getMessage() == ExtraValue.EVENTBUS_REPAIR_ADDSUCCESS ||//添加报修成功
                    eventRepair.getMessage() == ExtraValue.EVENTBUS_UPLOAD_OWNER_USERSIGNIMG) {//业主自己上传完毕签字文字

                //LogUtils.d("itchen--物业报修列表收到了详情发送的刷新消息--EVENTBUS_UPLOAD_OWNER_USERSIGNIMG");
                gainDatas();

            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            jumpFromFlag = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);
        }

    }

    private void showAlertViewPhoneNumber(final String _phoneNumber) {

        CommUtils.checkDialog(mAlertView);

        mAlertView = new AlertView(null,//
                _phoneNumber, //
                ConstantSign.ALERTVIEW_LEFT_CANCEL,//
                new String[]{ConstantSign.ALERTVIEW_RIGHT_COPY_INFORMATION}, //
                null, //
                PropertyRepairActivity.this, //
                AlertView.Style.Alert,//
                new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                    @Override
                    public void onItemClick(Object o, int position) {

                        if (position != AlertView.CANCELPOSITION) {

                            PropertyRepairActivity.this.startActivity(CommUtils.callThePhoneNumAction_dial(_phoneNumber));

//                            if (!AndPermission.hasPermissions(mActivityInstance, Permission.CALL_PHONE)) {
//
//                                CommUtils.authorityRequest(mActivityInstance, ConstantApi.MATERIALDIALOG_AUTHORITY_CONTENT_CALLPHONE, new AuthorityCallbackListener() {
//                                    @Override
//                                    public void doSomeThing() {
//                                        //如果不是取消
//                                        AndPermission.with(PropertyRepairActivity.this)
//                                                .runtime()
//                                                .permission(Permission.CALL_PHONE)
//                                                .rationale(new RuntimeRationale())
//                                                .onGranted(new Action<List<String>>() {
//                                                    @Override
//                                                    public void onAction(List<String> permissions) {
//
//                                                        PropertyRepairActivity.this.startActivity(CommUtils.callThePhoneNum(_phoneNumber));
//
//                                                    }
//                                                }).onDenied(new Action<List<String>>() {
//                                                    @Override
//                                                    public void onAction(List<String> permissions) {
//                                                        if (AndPermission.hasAlwaysDeniedPermission(PropertyRepairActivity.this, permissions)) {
//                                                            mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, PropertyRepairActivity.this, permissions);
//                                                        }
//                                                    }
//                                                }).start();
//                                    }
//                                });
//
//                            } else {
//                                PropertyRepairActivity.this.startActivity(CommUtils.callThePhoneNum(_phoneNumber));
//                            }

                        }

                    }
                });

        mAlertView.setCancelable(true).show();

    }

}